<template>
  <div class="dept-management">
    <a-card>
      <!-- 搜索表单 -->
      <a-form layout="inline" :model="queryParams" class="search-form">
        <a-form-item :label="t('dept.deptName')">
          <a-input v-model:value="queryParams.deptName" :placeholder="t('dept.deptName')" allow-clear />
        </a-form-item>
        <a-form-item :label="t('dept.status')">
          <a-select v-model:value="queryParams.status" :placeholder="t('dept.status')" allow-clear>
            <a-select-option :value="1">{{ t('common.normal') }}</a-select-option>
            <a-select-option :value="0">{{ t('common.disabled') }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button type="primary" @click="handleSearch">
              <template #icon><search-outlined /></template>
              {{ t('common.search') }}
            </a-button>
            <a-button @click="handleReset">
              <template #icon><redo-outlined /></template>
              {{ t('common.reset') }}
            </a-button>
          </a-space>
        </a-form-item>
      </a-form>

      <!-- 操作按钮 -->
      <div class="table-operations">
        <a-space>
          <a-button type="primary" @click="handleAdd">
            <template #icon><plus-outlined /></template>
            {{ t('common.add') }}
          </a-button>
        </a-space>
      </div>

      <!-- 数据表格 -->
      <a-table
        :columns="columns"
        :data-source="tableData"
        :loading="loading"
        :pagination="false"
        :row-key="record => record.id"
        :default-expand-all-rows="true"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'status'">
            <a-tag :color="record.status === 1 ? 'success' : 'error'">
              {{ record.status === 1 ? t('common.normal') : t('common.disabled') }}
            </a-tag>
          </template>
          <template v-if="column.key === 'action'">
            <a-space>
              <a @click="handleAdd(record)">{{ t('common.add') }}</a>
              <a-divider type="vertical" />
              <a @click="handleEdit(record)">{{ t('common.edit') }}</a>
              <a-divider type="vertical" />
              <a-popconfirm
                :title="t('dept.confirmDelete')"
                @confirm="handleDelete(record)"
              >
                <a class="danger-link">{{ t('common.delete') }}</a>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 新增/编辑弹窗 -->
    <a-modal
      v-model:visible="modalVisible"
      :title="modalTitle"
      @ok="handleModalOk"
      @cancel="handleModalCancel"
      :width="600"
    >
      <a-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }"
      >
        <a-form-item :label="t('dept.parentDept')" name="parentId">
          <a-tree-select
            v-model:value="formData.parentId"
            :tree-data="deptTree"
            :field-names="{
              children: 'children',
              label: 'deptName',
              value: 'id'
            }"
            :placeholder="t('dept.parentDept')"
            allow-clear
            tree-default-expand-all
          />
        </a-form-item>
        <a-form-item :label="t('dept.deptName')" name="deptName">
          <a-input v-model:value="formData.deptName" :placeholder="t('dept.deptName')" />
        </a-form-item>
        <a-form-item :label="t('dept.leader')" name="leader">
          <a-input v-model:value="formData.leader" :placeholder="t('dept.leader')" />
        </a-form-item>
        <a-form-item :label="t('dept.phone')" name="phone">
          <a-input v-model:value="formData.phone" :placeholder="t('dept.phone')" />
        </a-form-item>
        <a-form-item :label="t('dept.email')" name="email">
          <a-input v-model:value="formData.email" :placeholder="t('dept.email')" />
        </a-form-item>
        <a-form-item :label="t('dept.sort')" name="sort">
          <a-input-number v-model:value="formData.sort" :min="0" :max="999" />
        </a-form-item>
        <a-form-item :label="t('dept.status')" name="status">
          <a-radio-group v-model:value="formData.status">
            <a-radio :value="1">{{ t('common.normal') }}</a-radio>
            <a-radio :value="0">{{ t('common.disabled') }}</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import type { FormInstance } from 'ant-design-vue'
import {
  SearchOutlined,
  RedoOutlined,
  PlusOutlined
} from '@ant-design/icons-vue'
import type { DeptInfo, DeptQuery, DeptTreeNode } from '@/types/dept.type'
import {
  getDeptList,
  getDeptTree,
  createDept,
  updateDept,
  deleteDept
} from '@/api/dept'
import { useI18n } from 'vue-i18n'

const { t } = useI18n()

// 查询参数
const queryParams = reactive<DeptQuery>({
  deptName: '',
  status: undefined
})

// 表格列定义
const columns = [
  {
    title: t('dept.deptName'),
    dataIndex: 'deptName',
    key: 'deptName',
    width: 200
  },
  {
    title: t('dept.sort'),
    dataIndex: 'sort',
    key: 'sort',
    width: 80
  },
  {
    title: t('dept.leader'),
    dataIndex: 'leader',
    key: 'leader',
    width: 120
  },
  {
    title: t('dept.phone'),
    dataIndex: 'phone',
    key: 'phone',
    width: 120
  },
  {
    title: t('dept.email'),
    dataIndex: 'email',
    key: 'email',
    width: 180
  },
  {
    title: t('dept.status'),
    dataIndex: 'status',
    key: 'status',
    width: 100
  },
  {
    title: t('dept.createTime'),
    dataIndex: 'createTime',
    key: 'createTime',
    width: 180
  },
  {
    title: t('common.action'),
    key: 'action',
    width: 200
  }
]

// 表格数据
const tableData = ref<DeptTreeNode[]>([])
const deptTree = ref<DeptTreeNode[]>([])
const loading = ref(false)

// 表单相关
const formRef = ref<FormInstance>()
const modalVisible = ref(false)
const modalTitle = ref('')
const formData = reactive<Partial<DeptInfo>>({
  parentId: undefined,
  deptName: '',
  leader: '',
  phone: '',
  email: '',
  sort: 0,
  status: 1
})

// 表单校验规则
const rules = {
  deptName: [{ required: true, message: '请输入部门名称' }],
  sort: [{ required: true, message: '请输入排序号' }],
  status: [{ required: true, message: '请选择状态' }]
}

// 获取部门列表
const fetchData = async () => {
  loading.value = true
  try {
    const res = await getDeptTree()
    tableData.value = res.data
  } catch (error: any) {
    message.error(error.message || '获取部门列表失败')
  } finally {
    loading.value = false
  }
}

// 获取部门树
const fetchDeptTree = async () => {
  try {
    const res = await getDeptTree()
    deptTree.value = res.data
  } catch (error: any) {
    message.error(error.message || '获取部门树失败')
  }
}

// 搜索
const handleSearch = () => {
  fetchData()
}

// 重置
const handleReset = () => {
  queryParams.deptName = ''
  queryParams.status = undefined
  handleSearch()
}

// 新增
const handleAdd = (record?: DeptInfo) => {
  modalTitle.value = '新增部门'
  Object.assign(formData, {
    parentId: record?.id,
    deptName: '',
    leader: '',
    phone: '',
    email: '',
    sort: 0,
    status: 1
  })
  modalVisible.value = true
}

// 编辑
const handleEdit = (record: DeptInfo) => {
  modalTitle.value = '编辑部门'
  Object.assign(formData, record)
  modalVisible.value = true
}

// 删除
const handleDelete = async (record: DeptInfo) => {
  try {
    await deleteDept(record.id)
    message.success('删除成功')
    fetchData()
  } catch (error: any) {
    message.error(error.message || '删除失败')
  }
}

// 弹窗确认
const handleModalOk = async () => {
  try {
    await formRef.value?.validate()
    if (formData.id) {
      await updateDept(formData as DeptInfo)
      message.success('更新成功')
    } else {
      await createDept(formData as Omit<DeptInfo, 'id'>)
      message.success('创建成功')
    }
    modalVisible.value = false
    fetchData()
  } catch (error: any) {
    if (error.errorFields) {
      return
    }
    message.error(error.message || '操作失败')
  }
}

// 弹窗取消
const handleModalCancel = () => {
  modalVisible.value = false
  formRef.value?.resetFields()
}

onMounted(() => {
  fetchData()
  fetchDeptTree()
})
</script>

<style lang="less" scoped>
.dept-management {
  .search-form {
    margin-bottom: 16px;
  }

  .table-operations {
    margin-bottom: 16px;
  }

  .danger-link {
    color: #ff4d4f;
  }
}
</style> 